package lx.exalarm.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.util.List;

import lx.exalarm.alarm.ActionBean;
import lx.exalarm.alarm.AlarmBean;
import lx.exalarm.alarm.AlarmUtils;
import lx.exalarm.database.DBManager;
import lx.exalarm.utils.log.Log;

/**
 * Created by liuxu on 15-2-27.
 */
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String a = intent.getAction();
        if (a.equals(AlarmUtils.ACTION_ALARM)) {
            int alarmId = intent.getIntExtra(AlarmUtils.EXTRA_ALARM_ID, -1);
            Log.d("AlarmReceiver, receive ACTION_ALARM, alarmId=" + alarmId);
            if (alarmId == -1) {
                return;
            }
            AlarmBean alarm = DBManager.getInstance().getAlarm(alarmId);
            Log.d("AlarmReceiver, receive ACTION_ALARM, alarm=" + alarm);
            if (alarm == null) {
                return;
            }

            // find first enabled action
            ActionBean firstEnabledAction = alarm.getFirstEnabledAction();
            if (firstEnabledAction == null) {
                return;
            }
            if (firstEnabledAction.getInterval() == 0) {
                // no interval, start now
                AlarmUtils.startActivity(firstEnabledAction);
            } else {
                AlarmUtils.startAction(firstEnabledAction);
            }

            // set next alarm
            AlarmUtils.updateAlarm(alarm);

        } else if (a.equals(AlarmUtils.ACTION_ALARM_ACT)) {
            int actionId = intent.getIntExtra(AlarmUtils.EXTRA_ACTION_ID, -1);
            Log.d("AlarmReceiver, receive ACTION_ALARM_ACT, actionId=" + actionId);
            ActionBean action = DBManager.getInstance().getAction(actionId);
            Log.d("AlarmReceiver, receive ACTION_ALARM_ACT, action=" + action);
            if (action == null) {
                return;
            }
            AlarmUtils.startActivity(action);

        } else if (a.equals(Intent.ACTION_BOOT_COMPLETED)) {
            // update alarms after device boot
            List<AlarmBean> alarms = DBManager.getInstance().getAlarmList();
            if (alarms == null || alarms.size() == 0) {
                return;
            }
            for (AlarmBean alarm : alarms) {
                AlarmUtils.updateAlarm(alarm);
            }
        }
    }

}
